import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, TreeSelect, message } from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { createCategory, getCategoryTree } from '@/services/categoryApi';

const CategoryCreate: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [treeData, setTreeData] = useState<any[]>([]);

  // 获取分类树
  const fetchCategoryTree = async () => {
    try {
      const res = await getCategoryTree();
      setTreeData(res.data);
    } catch (error) {
      message.error('获取分类树失败');
    }
  };

  useEffect(() => {
    fetchCategoryTree();
  }, []);

  // 提交表单
  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      await createCategory(values);
      message.success('创建成功');
      history.push('/categories/list');
    } catch (error) {
      message.error('创建失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => history.push('/categories/list')}
        >
          返回列表
        </Button>
      </Card>

      <Card title="新增分类">
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            name="parent"
            label="父级分类"
          >
            <TreeSelect
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={treeData}
              placeholder="请选择父级分类"
              treeDefaultExpandAll
              allowClear
            />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={4} placeholder="请输入分类描述" />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              icon={<SaveOutlined />}
              loading={loading}
            >
              创建分类
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default CategoryCreate;